package com.javen.springbootneo4j.service.impl;

import com.javen.springbootneo4j.entity.node.City;
import com.javen.springbootneo4j.entity.node.Person;
import com.javen.springbootneo4j.entity.relation.LivesIn;
import com.javen.springbootneo4j.repository.CityRepository;
import com.javen.springbootneo4j.repository.LivesInRepository;
import com.javen.springbootneo4j.repository.PersonRepository;
import com.javen.springbootneo4j.service.LivesInService;
import com.javen.springbootneo4j.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Description: com.javen.springbootneo4j.service.impl
 * @Author: tujw@netinnet.cn
 * @Date: 2024/2/28 13:48
 */
@Service
public class LivesInServiceImpl implements LivesInService {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private CityRepository cityRepository;

    @Autowired
    private LivesInRepository livesInRepository;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public LivesIn livesInPersonToCity(String personName, String cityName) {
        Person person = personRepository.findByName(personName).orElse(null);
        City city = cityRepository.findByName(cityName).orElse(null);
        if (Objects.isNull(person) || Objects.isNull(city)) {
            return null;
        }
        LivesIn livesIn = new LivesIn();
        livesIn.setPerson(person);
        livesIn.setCity(city);
//        person.getLivesInRelations().add(livesIn);
//        person.setCity(city);
        // 保存或更新Person时，其与City之间的关系也会被自动处理
        return livesInRepository.save(livesIn);
    }

    // 其他业务逻辑...

}
